<template>
  <view class="root">
    <view v-if="loaded" class="blog-container">
      <text class="blog-title">{{ blog.title }}</text>
      <text class="blog-author">{{ blog.user.nickName }} @ {{ blog.createTime }}</text>
      <rich-text :nodes="blog.content" class="blog-content"></rich-text>
      <image :src="blog.picture" mode="widthFix" class="img item-pic"></image>
      <view>
        <text v-for="(tag,idx) in  blog.tags" :key="idx" class="item-tag">{{ tag }}</text>
      </view>
      <image :src="blog.user.avatar" mode="aspectFill" class="img-head"></image>
      <view class="icon-container">
        <image @click.stop="changeGood(blog.id,false)" v-if="hasGood"
               class="iconfont icon-yidongduan_yidianzan icon "></image>
        <image @click.stop="changeGood(blog.id,true)" v-else class="iconfont icon-dianzan icon"></image>
        <text class="icon-text">{{ blog.good }}</text>
        <image class="iconfont icon-pinglun icon"></image>
        <text class="icon-text">{{ blog.comments.length }}</text>
        <image class="iconfont icon-icon- icon"></image>
        <text class="icon-text">{{ blog.readCount }}</text>
      </view>
    </view>
    <!--    评论展示-->
    <view v-if="hasComments" class="blog-container">
      <view v-for="(item,index) in parents" :key="item.id">
        <view class="parent-container">
          <text class="cmt-author">{{ item.nickName }}</text>
          <view class="cmt-time-container">
            <text class="cmt-time">{{ item.createTime }}</text>
            <text v-if="canDelete(item)" class="txt-delete" @click="deleteCmt(item,true,index)">[删除]</text>
          </view>
          <image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
          <text class="cmt-content" @click="clickToReply(item)">{{ item.content }}</text>
        </view>
        <view v-if="replies[index].length>0" class="replies-container">
          <view v-for="(reply,idx) in replies[index]" :key="reply.id" class="reply-item">
            <view class="reply-info">
              <text class="reply-author">{{reply.nickName}}</text>
              <text class="reply-to">@{{reply.toUser}}</text>
              <text class="reply-time">{{reply.createTime}}</text>
              <text v-if="canDelete(reply)" class="txt-delete" @click.stop="deleteCmt(reply,false,index)">[删除]</text>
            </view>
			        <text class="reply-content"  @click="clickToReply(reply)" >{{reply.content}}</text>
          </view>
        </view>
        <view v-if="index<parents.length-1" class="cmt-line"></view>
      </view>

    </view>
    <!--回复评论-->
    <view class="input-container">
      <image :src="userAvatar" class="input-avatar" @click="clickLogin" ></image>
      <textarea auto-height v-model:class="inputValue" :placeholder="inputHolder" class="input-area"
                placeholder-class="input-holder"  @input="inputGetValue"></textarea>
      <image src="../../static/icons/commit.png" class="input-commit" @click="clickCommit"></image>
    </view>
    <login-dialog ref="login" @after="afterLogin"></login-dialog>

  </view>
</template>

<script>
import blogVue from './blog.vue'
import LoginDialog from "../../components/login-dialog/login-dialog.vue";
let parentId=null
let cmtValue=""
let app=getApp()
export default {
  components: {LoginDialog},
  data() {
    return {
      id: '',
      blog: [],
      hasGood: false,
      loaded: false,
      parents: [],
      replies: [],
      hasComments: false, //判断有没有评论
      inputValue:'',
      inputHolder:'请输入评论内容.......',
      good_ids: [],
      userAvatar:"../../static/icons/default_user.png",

    }
  },
  onLoad(options) {
    let id = options.id
    let good_ids = uni.getStorageSync(this.$params.key_good_ids)
    if (good_ids) {
      this.hasGood = good_ids.indexOf(id) >= 0
    }
    this.addReadCount(id)
    this.$noti.add(this.$params.noti_login_status, this.afterLogin,this)
  },
  onUnload(){
    this.$noti.remove(this.$params.noti_login_status, this)
  },
  methods: {
    deleteCmt(cmt,isParent,index){
      let url=this.$params.host+this.$params.action_delete_comment+cmt.id
      let data={
        token:app.globalData.token
      }
      uni.showModal({
        title:'删除评论',
        content:'确认删除该评论？\n此操作子评论也会被删除',
        showCancel:true,
        cancelText: '算了',
        confirmText: '删除',
        success:res=>{
          if (res.confirm){
            uni.showLoading({
              title:'删除评论....',
              mask:false
            });
            this.$request.del(url,data,res=>{
              uni.showToast({
                title:res.message,
                icon:'none'
              });
              if (res.success){
                if (isParent){
                  let list=this.replies[index]
                  list.push(this.parents[index])
                  this.$util.remove(this.parents,index)
                  this.$util.remove(this.replies,index)
                  this.blog.comments=this.blog.comments.filter(c=>list.every(r=>r.id!==c.id))
                }else {
                  let children=this.getChildren(cmt,this.replies[index])
                  children.push(cmt)
                  this.replies[index]=this.replies[index].filter(r=>children.every(c=>c.id!=r.id))
                  this.blog.comments=this.blog.comments.filter(c=>children.every(r=>r.id!==c.id))
                }
              }
              //刷新评论列表页
              this.$noti.post(this.$params.noti_comment_count,{
                id:this.blog.id,
                comments:this.blog.comments,
              })
            },() => {

             uni.hideLoading()
            })
          }
        },
        // fail:()=>{},
        // complete:()=>{}
      })

    },
    // 回复评论
    clickCommit(){
      //1.判断是否登录
      if (app.globalData.token.length==0){
        console.log(cmtValue)
        this.$refs.login.show()
        return
      }
      //2.判断数据非空合法性
      if (cmtValue.length==0){
        uni.showToast({
          title:'请输入评论的内容',
          icon:'none'
        })
        return;
      }
      //3.发送请求
      let url=this.$params.host+this.$params.action_add_comment
      let data={
        nick_name:app.globalData.nickName,
        avatar: "/" + app.globalData.avatar,
        email: app.globalData.email,
        content:cmtValue,
        blog_id:this.blog.id,
        parent_id:parentId,
        token:app.globalData.token,
        is_owner:app.globalData.uid == this.blog.user.id
      }
      //4.刷新评论列表
      this.$request.post(url,data,res=>{
       if (!res.success){
         uni.showToast({
           title:res.message,
           icon:'none'
         })
         return
       }
       let  cmt={}
       cmt.blogId=res.data.blogId
       cmt.token=res.data.token
        cmt.content = res.data.content
       cmt.avatar=res.data.avatar
       cmt.createTime=res.data.createTime
       cmt.nickName=res.data.nickName
        cmt.owner=res.data.owner
        cmt.id=res.data.id
        cmt.parentId=res.data.parentId
        cmt.email=res.data.email
        let comments=this.blog.comments.concat(cmt)
        this.blog.comments=comments
        this.formatComments(comments)
        this.hasComments=this.blog.comments.length>0
        this.inputHolder="请输入评论内容......."
        this.inputValue=""

        cmtValue=""
        parentId=null
        //刷新评论列表页
        this.$noti.post(this.$params.noti_comment_count,{
          id:this.blog.id,
          comments:comments,
        })
      } ,() => {
      })
    },
    afterLogin(){
      this.userAvatar=this.$params.host+getApp().globalData.avatar
      console.log(this.userAvatar)
    },
    clickLogin(){
      this.$refs.login.show()
    },
    addReadCount(id) {
      let url = this.$params.host + this.$params.action_read_count
      let data = {
        "id": id
      }
      this.$request.postParam(url, data, res => {
        let count = res.data
        // console.log(res)
        // console.log(count)
        // 第一种方式，获取上一页面实例
        // this.refreshPreviousPage(id,count)
        // 第二种方式：使用通知中心解耦
        this.$noti.post(this.$params.noti_refresh_count, {
          id,
          count
        })
      }, () => {
        this.getBlog(id)
      })
    },
    // 刷新上一页
    refreshPreviousPage(id, count) {
      let pages = getCurrentPages()
      let prev = pages[pages.length - 2]
      prev.refreshReadCount(id, count)

    },
    getBlog(id) {
      let url = this.$params.host + this.$params.action_blog + id
      this.$request.get(url, res => {
        this.loaded = true
        let blog = res.data
        this.blog = res.data

        this.hasComments = blog.comments.length > 0
        uni.setNavigationBarTitle({
          title: this.blog.user.nickName
        })


        if (!this.blog.picture.startsWith("http")) {
          blog.picture = this.$params.host + blog.picture
        }
        blog.user.avatar = this.$params.host + blog.user.avatar
        blog.content = blog.content.replace(/\<img/gi, '<img class="img" ')
        blog.createTime = this.$util.formatTime(new Date(blog.createTime))
        this.blog = blog
        this.formatComments(this.blog.comments)
      }, () => {
      })
    },
    // 获取评论信息
    formatComments(comments) {
      if (comments.length == 0) {
        return
      }
      // console.log(comments.length)
      let rootComments = []
      // 遍历所有根评论
      comments.forEach(c => {
        if (c.avatar.startsWith("/http")) {
          // c.avatar = this.$params.host + c.avatar.substring(1)
          c.avatar =c.avatar.substring(1)
        }else {
          c.avatar = this.$params.host + c.avatar.substring(1)
        }
        c.createTime = this.$util.formatTime(new Date(c.createTime))
        if (c.parentId == null) {
          rootComments.push(c)
        }
      })
      //排序
      rootComments.sort((c1, c2) => {
        return new Date(c2.createTime).getTime() - new Date(c1.createTime).getTime()
      })
      let replies = new Array(rootComments.length).fill([])
      let index = 0
      // 找到根评论所有的子评论
      rootComments.forEach(r => {
        let cmmts = []
        cmmts = cmmts.concat(this.getChildren(r, comments))
        replies[index++] = cmmts
        // 过滤
        comments = comments.filter(c => cmmts.every(cc => cc.id != c.id))
      })
      this.parents = rootComments
      this.replies = replies
    },
    getChildren(parent, comments) {
      //todo:得到parent所有的子评论
      let childrenComments = [];
      comments.forEach(comment => {
        // 如果parentId=父评论id
        if (parent.id == comment.parentId) {
          comment.toUser = parent.nickName
          childrenComments.push(comment)
          // 过滤
          let cmmts = comments.filter(cmt => cmt.id != comment.id)
          childrenComments.concat(this.getChildren(comment, cmmts))
        }
      })
      return childrenComments;

    },
    canDelete(item) {
      return app.globalData.type ==1 || item.avatar==this.userAvatar
    },
    //点赞方法

    changeGood (id, isGood) {
      let url = this.$params.host
      let action = isGood ? this.$params.action_good : this.$params.action_del_good
      url += action
      // console.log(this.blog.id);
      let data = {
        "id": id
      }
      this.$request.postParam(url, data, res => {
        let good_ids = uni.getStorageSync(this.$params.key_good_ids)
        if (!Array.isArray(good_ids)) {
          good_ids = []
        }
        if (this.hasGood) {
          good_ids = good_ids.filter(id => id != this.blog.id)
        } else {
          good_ids.push(this.blog.id)
        }
        uni.setStorageSync(this.$params.key_good_ids, good_ids)
        this.hasGood = !this.hasGood
        this.blog.good = this.hasGood ? this.blog.good + 1 : this.blog.good - 1

        //通知主页修改点赞数
        this.$noti.post(this.$params.key_good_ids, {
          id: id,
          goodCount: this.blog.good
        })
      }, () => {
      })
    },
  // 回复
    clickToReply(item){
      parentId=item.id
      this.inputHolder='@'+item.nickName
    },
    // 获取评论值
    inputGetValue(e){
      // console.log(e)
      cmtValue=e.detail.value
      // console.log(cmtValue)

    }

  }
}
</script>

<style>
@import url("blog.css");
</style>